package com.atguigu.gmall.comment.service.impl;

import com.atguigu.gmall.comment.repository.CommentInfoRepository;
import com.atguigu.gmall.comment.service.CommentInfoService;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.model.comment.CommentInfo;
import com.atguigu.gmall.model.comment.CommentInfoAppraiseVo;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.product.SkuInfo;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author atguigu-mqx
 */
@Service
public class CommentInfoServiceImpl implements CommentInfoService {
    @Autowired
    private CommentInfoRepository commentInfoRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Override
    public void saveCommentInfo(List<CommentInfo> commentInfoList, Long userId) {
        //  获取订单Id
        Long orderId = commentInfoList.get(0).getOrderId();
        //  获取订单信息
        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
        //  判断用户
        if(orderInfo.getUserId().longValue() != userId.longValue()) {
            throw new GmallException(ResultCodeEnum.ILLEGAL_REQUEST);
        }
        //  通过userId 获取用户信息！
        UserInfo userInfo = userFeignClient.getUserInfo(userId.toString());
        //  赋值的操作！
        for (CommentInfo commentInfo : commentInfoList) {
            commentInfo.setUserId(userId);
            commentInfo.setCreateTime(new Date());
            commentInfo.setUpdateTime(new Date());

            if(null != userInfo) {
                commentInfo.setNickName(userInfo.getNickName());
                commentInfo.setHeadImg(userInfo.getHeadImg());
            }
            SkuInfo skuInfo = productFeignClient.getSkuInfo(commentInfo.getSkuId());
            if(null != skuInfo) {
                commentInfo.setSpuId(skuInfo.getSpuId());
            }
        }
        //  保存用户的评论内容
        commentInfoRepository.saveAll(commentInfoList);

        //更新订单状态
        orderFeignClient.updateCommnetStatus(orderId);
    }

    @Override
    public IPage<CommentInfo> selectPage(Integer page, Integer limit, Long spuId) {
        //  根据什么条件查询：
        Query query = Query.query(Criteria.where("spuId").is(spuId));
        PageRequest pageRequest = PageRequest.of(page-1, limit);
        query.with(pageRequest);
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        query.with(sort);

        List<CommentInfo> commentInfoList = mongoTemplate.find(query, CommentInfo.class);
        //  计算总条数公式
        long total = mongoTemplate.count(query.limit(-1).skip(-1L), CommentInfo.class);

        return new Page(page,limit,total).setRecords(commentInfoList);
    }

    @Override
    public Map<String, Object> countBySpuId(Long spuId) {
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("spuId").is(spuId)),
                Aggregation.group("appraise")
                        .first("appraise").as("appraise")
                        .count().as("count"),
                Aggregation.sort(Sort.by(Sort.Direction.DESC, "appraise")));

        AggregationResults<CommentInfoAppraiseVo> aggregationResults = mongoTemplate.aggregate(agg, CommentInfo.class, CommentInfoAppraiseVo.class);
        List<CommentInfoAppraiseVo> commentInfoAppraiseVoList = aggregationResults.getMappedResults();

        Map<String, Object> map = new HashMap<>();
        if(!CollectionUtils.isEmpty(commentInfoAppraiseVoList)) {
            int sum1 = commentInfoAppraiseVoList.stream().filter(commentInfoAppraiseVo ->
                    commentInfoAppraiseVo.getAppraise() == 1 || commentInfoAppraiseVo.getAppraise() == 2)
                    .mapToInt(commentInfoAppraiseVo -> commentInfoAppraiseVo.getCount()).sum();

            int sum2 = commentInfoAppraiseVoList.stream().filter(commentInfoAppraiseVo ->
                    commentInfoAppraiseVo.getAppraise() == 3 || commentInfoAppraiseVo.getAppraise() == 4)
                    .mapToInt(commentInfoAppraiseVo -> commentInfoAppraiseVo.getCount()).sum();

            int sum3 = commentInfoAppraiseVoList.stream().filter(commentInfoAppraiseVo ->
                    commentInfoAppraiseVo.getAppraise() == 5)
                    .mapToInt(commentInfoAppraiseVo -> commentInfoAppraiseVo.getCount()).sum();

            map.put("count1", sum1);
            map.put("count2", sum2);
            map.put("count3", sum3);
            int count = sum1 + sum2 + sum3;
            map.put("count", count);
            BigDecimal rate = new BigDecimal(sum3).divide(new BigDecimal(count), 2, BigDecimal.ROUND_HALF_EVEN).multiply(new BigDecimal(100));
            map.put("rate", rate.intValue()+"%");
        } else {
            map.put("count1", 0);
            map.put("count2", 0);
            map.put("count3", 0);
            map.put("count", 0);
            map.put("rate", "0%");
        }

        return map;
    }
}
